package com.masonluo.mlonlinejudge.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.masonluo.mlonlinejudge.constant.SystemConstant;
import com.masonluo.mlonlinejudge.enums.TokenType;
import com.masonluo.mlonlinejudge.exceptions.TokenVerifyException;
import com.masonluo.mlonlinejudge.security.Token;

/**
 * @author masonluo
 * @date 2021/5/6 6:09 下午
 */
public class TokenUtils {

    private static final ObjectMapper mapper = new ObjectMapper();

    public static Token convert(String base64Token) {
        String jsonToken = CodecUtils.base64Decode(base64Token);
        try {
            return mapper.readValue(jsonToken, Token.class);
        } catch (JsonProcessingException e) {
            throw new TokenVerifyException(String.format("The string [%s] does not the pattern of token", base64Token));
        }
    }

    public static String generateToken(String username, TokenType tokenType, long timestamp) {
        try {
            Token token = new Token(username, timestamp, tokenType, SystemConstant.TOKEN_KEY);
            String json = mapper.writeValueAsString(token);
            return CodecUtils.base64Encode(json);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
